package com.javadaemon.rpgengine.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import com.javadaemon.rpgengine.util.MapLoader.WorldObject;
import com.thoughtworks.xstream.XStream;


public class XStreamUtil {

    private static XStream xstream;

    /**
     * Gets the XStream.
     * 
     * @return The xstream instance.
     */
    public static XStream getXStream() {
	return xstream;
    }

    /**
     * Initializes the XStream. Aliases the classes to the xml data.
     */
    static {
	if (getXStream() == null) {
	    xstream = new XStream();
	    xstream.alias("WorldObject", WorldObject.class);
	}
    }

    /**
     * Writes the XML file, using try and finally will allow the file output to close if an exception is thrown (will stop memory leaks)
     * 
     * @param object
     *            The object getting written
     * @param file
     *            The file area and name
     * @throws IOException
     */
    public static void writeXML(Object object, File file) throws IOException {
	FileOutputStream out = new FileOutputStream(file);
	try {
	    xstream.toXML(object, out);
	    out.flush();
	} finally {
	    out.close();
	}
    }

    /**
     * Writes the XML file, using try and finally will allow the file output to close if an exception is thrown (will stop memory leaks)
     * 
     * @param object
     *            The object getting written
     * @return The XML
     */
    public static String writeXML(Object object) {
	return xstream.toXML(object);
    }

    /**
     * Reads an object from an XML file.
     * 
     * @param file
     *            The file.
     * @return The object.
     * @throws IOException
     *             if an I/O error occurs. Edit: Now uses generic's
     */
    @SuppressWarnings("unchecked")
    public static <T> T readXML(File file) throws IOException {
	FileInputStream in = new FileInputStream(file);
	try {
	    return (T) xstream.fromXML(in);
	} finally {
	    in.close();
	}
    }

    /**
     * Reads an object from an XML string.
     * 
     * @param s
     *            The XML.
     * @return The object. Edit: Now uses generic's
     */
    @SuppressWarnings("unchecked")
    public static <T> T readXML(String s) {
	return (T) xstream.fromXML(s);

    }
}
